﻿using DocumentFormat.OpenXml.Spreadsheet;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Commn.TokenModule;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Service.Inventory;
using DongFangGuoKai.WMSPlatform.Service.Inventory.DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using SqlSugar;
using System.Linq.Expressions;
using XAct.Messages;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers.Inventory
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InventoryController : BaseController
    {
        private readonly IInventoryService inventoryService;
        private readonly ILogger<InventoryController> invenlogger;

        private readonly SimpleRepositroy<TInventories> inventoryrepost;
        private readonly IConfiguration configuration;
        private readonly SimpleRepositroy<TCells> cellrepost;

        public InventoryController(IInventoryService inventoryService, ILogger<InventoryController> invenlogger, SimpleRepositroy<TInventories> inventoryrepost, IConfiguration configuration)
        {
            this.inventoryService = inventoryService;
            this.invenlogger = invenlogger;

            this.inventoryrepost = inventoryrepost;
            this.configuration = configuration;
            cellrepost = inventoryrepost.ChangeRepository<SimpleRepositroy<TCells>>();
        }

        /// <summary>
        /// 物资管理系统同步库存数据
        /// </summary>
        /// <param name="inventoryDTOs"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SynchronousInventory(List<SynchronousInventoryDTO> inventoryDTOs)
        {
            if (inventoryDTOs.Count <= 0)
            {
                return Failed("参数有误!",400);
            }
            var IsOk = inventoryService.SynchronousInventory(inventoryDTOs, LocationCode: null, out string Msg);
            if (IsOk)
            {
                invenlogger.LogInformation("物资库存同步成功，" + Msg + ",入参为" + inventoryDTOs.ToJson());
                return Success("保存成功！");
            }
            invenlogger.LogError("物资库存同步失败，" + Msg + ",入参为" + inventoryDTOs.ToJson());
            return Failed(Msg);
        }

        /// <summary>
        /// 根据货位同步库存数据
        /// </summary>
        /// <param name="LocationCode"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CellSynchronizeInventory(string LocationCode)
        {
            if (string.IsNullOrEmpty(LocationCode))
            {
                return Failed("未查询到库位");
            }
            var cell = cellrepost.GetFirst(c => c.Code == LocationCode);
            if (cell == null)
            {
                invenlogger.LogError("未查询到库位,入参为" + LocationCode);
                return Failed("未查询到库位");
            }
            var url = configuration["HNBaseUrl"];
            if (url == null)
            {
                invenlogger.LogError("未获取到物资系统地址,入参为" + LocationCode);
                return Failed("未获取到物资系统地址");
            }
            //请求数据
            string hnBaseUrl = url;
            //var token = await TokenHelper.GetToken(hnBaseUrl);
            using var client = new HttpClient();
            //client.DefaultRequestHeaders.Add("Authorization", token);
            // 发送GET请求
            HttpResponseMessage response = await client.GetAsync(hnBaseUrl + "/railway/v1/pda/store/stock/page?locationCode=" + LocationCode); //修改为正确的地址

            var res = await response.Content.ReadAsStringAsync();
            var responseObject = JsonConvert.DeserializeObject<UpstreamData>(res);

            if (responseObject is null)
            {
                invenlogger.LogError("获取数据失败,入参为" + LocationCode);
                return Failed("获取数据失败!");
            }

            if (responseObject.Code != "200")
            {
                invenlogger.LogError("获取数据失败,物资系统返回错误" + responseObject.Msg + "入参为" + LocationCode);
                return Failed("获取数据失败,物资系统返回错误" + responseObject.Msg);
            }
            if (responseObject.Data is null)
            {
                invenlogger.LogError("获取数据失败入参为" + LocationCode);
                return Failed("获取数据失败!");
            }
            List<SynchronousInventoryDTO> synchronous = new List<SynchronousInventoryDTO>();
            if (responseObject.Data.List == null || responseObject.Data.List.Count <= 0)
            {
                invenlogger.LogError("获取数据失败,数据为空入参为" + LocationCode);
                return Failed("获取数据失败!");
            }
            foreach (var item in responseObject.Data.List)
            {
                synchronous.Add(new SynchronousInventoryDTO
                {
                    LocationName = item.StoreLocationRemark,
                    LocationCode = item.StoreLocationCode,
                    LocationId = item.StoreLocationId,
                    CreateDate = item.InputTime,
                    MaterialCode = item.MaterialCode,
                    MaterialName = item.MaterialName,
                    Qty = item.StockCount
                });
            }
            //添加数据
            var IsOk = inventoryService.SynchronousInventory(synchronous, LocationCode, out string Msg);
            if (IsOk)
            {
                invenlogger.LogInformation("物资库存同步成功，" + Msg + ",入参为" + LocationCode);
                return Success("保存成功！");
            }
            invenlogger.LogError("物资库存同步失败，" + Msg + ",入参为" + LocationCode);
            return Failed(Msg);
        }

        /// <summary>
        /// 获取库存数据
        /// </summary>
        /// <param name="LocationCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInventoryList(string? LocationCode)
        {
            Expressionable<TInventories> exp = Expressionable.Create<TInventories>();
            exp.AndIF(LocationCode != null, e => e.LocationCode == LocationCode);
            var inventoryList = inventoryrepost.GetList(exp.ToExpression());
            List<SynchronousInventoryDTO> synchronous = new();
            if (inventoryList != null)
            {
                foreach (var item in inventoryList)
                {
                    synchronous.Add(new SynchronousInventoryDTO()
                    {
                        CreateDate = item.CreateDate.Value,
                        LocationCode = item.LocationCode,
                        LocationId = item.LocationId.GetValueOrDefault(),
                        LocationName = item.LocationName,
                        MaterialCode = item.MaterialCode,
                        MaterialName = item.MaterialName,
                        Qty = (int)item.AvailableQty.GetValueOrDefault()
                    });
                }
                return Success(synchronous);
            }
            return Failed("无数据!");
        }
    }
}
